﻿#include "controler.h"
#include "ui_controler.h"
#include <QFileInfo>
#include <QDir>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include "gascontroler.h"
#include <QMessageBox>
#include <QDateTime>

QString Controler::ip = "192.168.2.1";
int Controler::gasInSwitchPort = 0;
int Controler::gasOutSwitchPort = 1;
int Controler::launchSwitchPort = 2;
int Controler::gasAnalogPort = 0;

float Controler::gasCoefficient = 1;
float Controler::zero = 0;
float Controler::default_  = 0.1;
int Controler::luanchTime  = 500;

float Controler::kp = 10000;
float Controler::ki = 0.001;
float Controler::kd = 0.001;

Controler::Controler(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Controler)
{
    ui->setupUi(this);
    loadSetDetails();
    utilsType = "gas";

    connect(set,&cortrolSet::save,this,&Controler::saveSetDetails);

    connect(launchTimer,&QTimer::timeout,this,[=](){
        if(openLaunchFlag){
            openLaunchFlag=false;
        }else{
            launchTimer->stop();
            bool flag = GasControler::client->setDigitalOutput(launchSwitchPort,false);
            // flag = true;
            if(flag) {
                ui->launch->setText("发射");
                ui->launch->setStyleSheet("background-color: rgb(255, 106, 92);border:2px solid #000000;");
                openLaunchFlag=false;
            }
        }
    });


    connect(inTimer,&QTimer::timeout,this,[=](){
        if(openInFlag){
            openInFlag=false;
        }else{
            inTimer->stop();
            bool flag = GasControler::client->setDigitalOutput(gasInSwitchPort,false);
            // flag = true;
            if(flag) {
                ui->switch_in->setText("进气阀");
                ui->switch_in->setStyleSheet("background-color: rgb(167, 255, 151);border:2px solid #000000;");
                openInFlag=false;

            }
        }
    });

    connect(outTimer,&QTimer::timeout,this,[=](){
        if(openOutFlag){
            openOutFlag=false;
        }else{
            outTimer->stop();
            bool flag = GasControler::client->setDigitalOutput(gasOutSwitchPort,false);
            // flag = true;
            if(flag) {
                ui->switch_out->setText("出气阀");
                ui->switch_out->setStyleSheet("background-color: rgb(255, 255, 170);border:2px solid #000000;");
                openOutFlag=false;
            }
        }
    });


    connect(autoInSwitch,&QTimer::timeout,this,[=](){
        if(!autoInFlag){
            turnOn(gasInSwitchPort);
            openInFlag = true;
        }else{
            turnOff(gasInSwitchPort);
            autoInSwitch->stop();
            openInFlag = false;
        }
        autoInFlag = !autoInFlag;
    });

    connect(autoOutSwitch,&QTimer::timeout,this,[=](){
        if(!autoOutFlag){
            turnOn(gasOutSwitchPort);
            openOutFlag = true;

        }else{
            turnOff(gasOutSwitchPort);
            autoOutSwitch->stop();
            openOutFlag = false;
        }
        autoOutFlag = !autoOutFlag;
    });

    connect(moveFlagTimer,&QTimer::timeout,this,[=](){
        if(tempFlag)
            ui->widget->setStyleSheet("background-color: yellow;"
                                        "font: 12pt 黑体;"
                                        "border:0px solid #000000;");
        else
            ui->widget->setStyleSheet("background-color: rgb(216, 246, 255);"
                                      "font: 12pt 黑体;");
        tempFlag = !tempFlag;
    });

    connect(timer,&QTimer::timeout,this,[=](){
        time = QDateTime::currentMSecsSinceEpoch()-time;
        float pidResult = pid->pidControl(currentValue,time);
        int openTime = 15;
        if(abs(historyValue-currentValue)<0.15) openTime=50;
        if(abs(historyValue-currentValue)>0.5) openTime=8;

        openTime = abs(pidResult)/15;

        if(pidResult>(default_+100)) {
            if(!autoInSwitch->isActive()) autoInSwitch->start(openTime-1);
            okCount = 0;
        }else if(pidResult<-(default_+100)){
            if(!autoOutSwitch->isActive()) autoOutSwitch->start(openTime);
            okCount = 0;
        }else{
            okCount++;
            ui->textDisplay->setText("尝试稳定气压");

            if(okCount>=15){
                ui->pressure_limit->click();
                okCount = 0;
                ui->textDisplay->setText("气压已稳定,等待发射");
                // emit option(QStringLiteral("气压稳定于%1,目标：%2").arg(value).arg(targetPressure));
            }
        }
        historyValue = currentValue;
    });
}

Controler::~Controler()
{
    delete ui;
}

void Controler::openAdmin(bool flag){
    set->openAdmin(flag);
}

void Controler::autoControl(QString cmd, QString value)
{
    if(cmd=="gasin"){
        if(value=="open")turnOn(gasInSwitchPort);
        else turnOff(gasInSwitchPort);
    }else if(cmd=="gasout"){
        if(value=="open")turnOn(gasOutSwitchPort);
        else turnOff(gasOutSwitchPort);
    }else if(cmd =="luanch"){
        ui->launch->click();
    }else if(cmd =="target"){
        ui->lineEdit_pressure_limit->setText(value);
    }else if(cmd =="stable"){
        ui->pressure_limit->click();
    }else if(cmd =="exhaust"){
        ui->gasOut->click();
    }else if(cmd=="luanchtime"){
        luanchTime = value.toInt();
    }else{
        emit option(QStringLiteral("No cmd called:'%1=%2' in %3").arg(cmd).arg(value).arg(utilsType+"-"+name));
    }

}

void Controler::readOutput(){
    if(GasControler::client->readDigitalOuput(gasInSwitchPort))turnOn(gasInSwitchPort);

    if(GasControler::client->readDigitalOuput(gasOutSwitchPort))turnOn(gasOutSwitchPort);

    if(GasControler::client->readDigitalOuput(launchSwitchPort)){
        ui->launch->setStyleSheet("background-color: yellow;border:2px solid #000000;");
        ui->launch->setText("重置");
        openLaunchFlag = !openLaunchFlag;
    }

}

void Controler::setMessageBox(QString message){
    QMessageBox msgBox;
    msgBox.setWindowTitle("提示");
    msgBox.setBaseSize(200,200);
    msgBox.setStyleSheet("QLabel{"
                         "min-width:200px;"
                         "min-height:80px; "
                         "font-size:22px;"
                         "}"
                         "QPushButton{font-size:22px;}");
    msgBox.setText(message);
    msgBox.setStandardButtons(QMessageBox::Ok);
    int ret = msgBox.exec();
    if(ret == QMessageBox::Ok){
        return;
    }
}
void Controler::loadSetDetails(){
    QString rootPath  = QCoreApplication::applicationDirPath();

    QFileInfo fileInfo(rootPath+"/log/"+userfilePath+"/gasSet.l");
    QString directoryPath = fileInfo.absolutePath();

    // 检查并创建文件夹（如果不存在）
    if (!QDir(directoryPath).exists()) {
        QDir().mkdir(directoryPath);
    }

    QFile file(rootPath+"/log/"+userfilePath+"/gasSet.l");

    if(!file.open(QIODevice::ReadOnly)){
        QJsonDocument jsonDoc;
        QString temp  = jsonDoc.toJson();

        file.open(QIODevice::WriteOnly);
        file.write(temp.toUtf8());
        file.close();
    }

    QByteArray jsonData = file.readAll();
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData);
    QJsonObject jsonObject = jsonDoc.object();

    gasInSwitchPort = jsonObject.value("gasInSwitchPort").toInt();
    gasOutSwitchPort = jsonObject.value("gasOutSwitchPort").toInt();
    launchSwitchPort = jsonObject.value("launchSwitchPort").toInt();
    gasAnalogPort = jsonObject.value("gasAnalogPort").toInt();
    gasCoefficient = jsonObject.value("gasCoefficient").toDouble();
    default_ = jsonObject.value("default").toDouble();
    zero = jsonObject.value("zero").toDouble();
    luanchTime = jsonObject.value("luanchTime").toInt();

    kp = jsonObject.value("kp").toDouble();
    ki = jsonObject.value("ki").toDouble();
    kd = jsonObject.value("kd").toDouble();


    if(jsonObject.value("ip").toString()!="") ip = jsonObject.value("ip").toString();


    file.close();
}

void Controler::saveSetDetails(){

    QString rootPath  = QCoreApplication::applicationDirPath();
    QFile file(rootPath+"/log/"+userfilePath+"/gasSet.l");

    QJsonObject *myObject = new QJsonObject;

    myObject->insert("gasInSwitchPort",gasInSwitchPort);
    myObject->insert("gasOutSwitchPort",gasOutSwitchPort);
    myObject->insert("launchSwitchPort",launchSwitchPort);
    myObject->insert("gasAnalogPort",gasAnalogPort);
    myObject->insert("gasCoefficient",gasCoefficient);
    myObject->insert("zero",zero);
    myObject->insert("default",default_);
    myObject->insert("ip",ip);
    myObject->insert("luanchTime",luanchTime);
    myObject->insert("kp",kp);
    myObject->insert("ki",ki);
    myObject->insert("kd",kd);


    QJsonDocument jsonDoc;
    jsonDoc.setObject(*myObject);

    QString temp  = jsonDoc.toJson();

    file.open(QIODevice::WriteOnly);
    file.write(temp.toUtf8());
    file.close();
}


void Controler::automaticStabilization(float target,float current, float fault){
    if(current<target){
        if(abs(current-target)>5){
            if(!autoInSwitch->isActive()) autoInSwitch->start(autoControlTime);
        }else if(5>=abs(current-target)>0.5){
           if(!autoInSwitch->isActive()) autoInSwitch->start(autoControlTime/50);
        }else if(0.5>=abs(current-target)>0.1){
            if(!autoInSwitch->isActive()) autoInSwitch->start(autoControlTime/250);
        }else {
            if(!autoInSwitch->isActive()) autoInSwitch->start(autoControlTime/10000);
        }
    }else if(current>(target+fault)){

        if(abs(current-(target+fault))>5){
            if(!autoOutSwitch->isActive()) autoOutSwitch->start(autoControlTime);
        }else if(5>=abs(current-(target+fault))>0.5){
            if(!autoOutSwitch->isActive()) autoOutSwitch->start(autoControlTime/50);
        }else if(0.5>=abs(current-(target+fault))>0.1){
            if(!autoOutSwitch->isActive()) autoOutSwitch->start(autoControlTime/250);
        }else{
            if(!autoOutSwitch->isActive()) autoOutSwitch->start(autoControlTime/1000);
        }
    }else{
        if(openInFlag){
            if(turnOff(gasInSwitchPort)) openInFlag = false;
        }else if(openOutFlag){
            if(turnOff(gasOutSwitchPort)) openOutFlag = false;
        }
    }

}

void Controler::setMoveFlag(bool flag)
{
    if(flag&&!moveFlagTimer->isActive()) moveFlagTimer->start(500);
    else if(!flag){
        moveFlagTimer->stop();
        ui->widget->setStyleSheet("font: 12pt 黑体;"
                                  "background-color: rgb(233, 231, 255);");
    }
}
void Controler::setGasValue(float value){
    if(value<0.001)value = 0;
    QString strValue = QString::number(value, 'g', 3);

    ui->pressure->setText(strValue);
    ui->pressure->setStyleSheet("font: 12pt 黑体;"
                                "font: 20pt Microsoft YaHei UI;");
    currentValue = value;

    if(value>0.3)setMoveFlag(true);
    else setMoveFlag(false);

    // if(autoCloseFlag){
    //     time = QDateTime::currentMSecsSinceEpoch()-time;
    //     float pidResult = pid->pidControl(currentValue,time);
    //     if(pidResult>default_) {
    //         if(!autoInSwitch->isActive()) autoInSwitch->start(10);
    //         // turnOn(gasInSwitchPort);
    //         // turnOff(gasOutSwitchPort);
    //         okCount = 0;
    //         ui->textDisplay->setText("稳定气压中");
    //     }else if(pidResult<-default_){
    //         if(!autoOutSwitch->isActive()) autoOutSwitch->start(10);
    //         // turnOn(gasOutSwitchPort);
    //         // turnOff(gasInSwitchPort);
    //         okCount = 0;
    //         ui->textDisplay->setText("稳定气压中");
    //     }else{
    //         okCount++;
    //         ui->textDisplay->setText("尝试稳定气压");

    //         turnOff(gasInSwitchPort);
    //         turnOff(gasOutSwitchPort);

    //         if(okCount>=100){
    //             ui->pressure_limit->click();
    //             okCount = 0;
    //             ui->textDisplay->setText("气压已稳定,等待发射");
    //             emit option(QStringLiteral("气压稳定于%1,目标：%2").arg(value).arg(targetPressure));
    //         }
    //     }
    // }
}

void Controler::setIp(QString ip, bool flag){
    if(flag){
        ui->connect_ip->setText(ip);
        ui->widget->setStyleSheet("font: 12pt 黑体;"
                                  "background-color: rgb(233, 231, 255);");
        ui->textDisplay->setText("连接成功");
        emit option(QStringLiteral("连接成功%1").arg(ip));
    }else {
        ui->connect_ip->setText("null");
        ui->widget->setStyleSheet("font: 12pt 黑体;"
                                  "background-color: rgb(161, 171, 187);");
        ui->textDisplay->setText("未连接");
    }
}

bool Controler::turnOn(int gasSwitch){
    bool flag = GasControler::client->setDigitalOutput(gasSwitch,true);

    if(flag) {
        if(gasSwitch==gasInSwitchPort){
            ui->switch_in->setStyleSheet("background-color: yellow;border:2px solid #000000;");
            ui->switch_in->setText("关闭");
        }else if (gasSwitch==gasOutSwitchPort){
            ui->switch_out->setStyleSheet("background-color: yellow;border:2px solid #000000;");
            ui->switch_out->setText("关闭");
        }

    }
    return flag;
}

bool Controler::turnOff(int gasSwitch){
    bool flag = GasControler::client->setDigitalOutput(gasSwitch,false);
    if(flag) {
        if(gasSwitch==gasInSwitchPort) {
            ui->switch_in->setText("进气阀");
            ui->switch_in->setStyleSheet("background-color: rgb(167, 255, 151);border:2px solid #000000;");
        }
        else if (gasSwitch==gasOutSwitchPort){
            ui->switch_out->setText("出气阀");
            ui->switch_out->setStyleSheet("background-color: rgb(255, 255, 170);border:2px solid #000000;");
        }
    }
    return flag;
}

void Controler::on_switch_in_clicked()
{
    //气体阀门开关
    if(!GasControler::client->isOpen()){
        setMessageBox("未连接");
        return;
    }

    if(openOutFlag){
        setMessageBox("出气阀未关闭！");
        return;
    }else if(openLaunchFlag){
        setMessageBox("发射阀未关闭！");
        return;
    }
    if(autoCloseFlag){
        setMessageBox("自动控制未关闭！");
        return;
    }

    if(openInFlag){
        if(turnOff(gasInSwitchPort)) openInFlag = false;
        inTimer->stop();
    }else{
        if(turnOn(gasInSwitchPort)) openInFlag = true;
        inTimer->start(10);
    }


}

void Controler::on_switch_out_clicked()
{
    //气体阀门开关
    if(!GasControler::client->isOpen()){
        setMessageBox("未连接");
        return;
    }

    if(openInFlag){
        setMessageBox("进气阀未关闭！");
        return;
    }else if(openLaunchFlag){
        setMessageBox("发射阀未关闭！");
        return;
    }

    if(autoCloseFlag){
        setMessageBox("自动控制未关闭！");
        return;
    }

    if(openOutFlag){
        if(turnOff(gasOutSwitchPort)) openOutFlag = false;
        outTimer->stop();
    }else{
        if(turnOn(gasOutSwitchPort)) openOutFlag = true;
        outTimer->start(10);
    }

}


void Controler::on_launch_clicked()
{
    //发射开关
    if(!GasControler::client->isOpen()){
        setMessageBox("未连接");
        return;
    }

    if(openInFlag||openOutFlag){
        setMessageBox("气阀未关闭！");
        return;
    }

    if(autoCloseFlag){
        setMessageBox("自动控制未关闭！");
        return;
    }

    if(!openLaunchFlag){
        bool flag = GasControler::client->setDigitalOutput(launchSwitchPort,true);
        if(flag) {
            ui->launch->setStyleSheet("background-color: yellow;border:2px solid #000000;");
            ui->launch->setText("重置");
            openLaunchFlag = !openLaunchFlag;
        }
        launchTimer->start(luanchTime/2);
    }else{
        launchTimer->stop();

        bool flag = GasControler::client->setDigitalOutput(launchSwitchPort,false);
        if(flag) {
            ui->launch->setText("发射");
            ui->launch->setStyleSheet("background-color: rgb(255, 106, 92);border:2px solid #000000;");
            openLaunchFlag = !openLaunchFlag;
        }

    }
// 4.73

}

void Controler::on_set_clicked()
{
    set->show();
}

void Controler::on_pressure_limit_clicked(bool checked)
{
    pid->setPidTag(kp,ki,kd,ui->lineEdit_pressure_limit->text().toFloat(),10000);

    if(checked) {
        timer->start(250);
        time = QDateTime::currentMSecsSinceEpoch();
    }
    else {
        timer->stop();
        turnOff(gasInSwitchPort);
        turnOff(gasOutSwitchPort);
    }
    // autoCloseFlag = checked;

    // if(!checked){
    //     turnOff(gasInSwitchPort);
    //     turnOff(gasOutSwitchPort);
    // }

    // ui->lineEdit_pressure_limit->setEnabled(!checked);
    // targetPressure = ui->lineEdit_pressure_limit->text().toFloat();
}


void Controler::on_gasOut_clicked()
{
    //气体阀门开关
    if(!GasControler::client->isOpen()){
        setMessageBox("未连接");
        return;
    }

    if(openInFlag){
        setMessageBox("进气阀未关闭！");
        return;
    }else if(openLaunchFlag){
        setMessageBox("发射阀未关闭！");
        return;
    }

    if(autoCloseFlag){
        setMessageBox("自动控制未关闭！");
        return;
    }

    if(openOutFlag){
        if(turnOff(gasOutSwitchPort)) openOutFlag = false;
        ui->gasOut->setText("排气");
        ui->gasOut->setStyleSheet("background-color: rgb(255, 106, 92);border:2px solid #000000;");
    }else{
        if(turnOn(gasOutSwitchPort)) openOutFlag = true;
        ui->gasOut->setText("排气中");
        ui->gasOut->setStyleSheet("background-color: yellow;border:2px solid #000000;");
    }
}

